import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:tin_flutter/app/res/intl.dart';
import 'package:tin_flutter/ui/activity/brand/detail/brand_detail_logic.dart';
import 'package:tin_flutter/ui/widget/common_product_vertical_widget.dart';

import '../../../../app/res/app_color.dart';

/// * 作者: Tao
/// * 日期: 2025/11/10
/// * 时间: 16:42
/// * 描述: 品牌推荐页面
class BrandDetailPage extends StatefulWidget {
  const BrandDetailPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _BrandDetailPageState();
}

class _BrandDetailPageState extends State<BrandDetailPage> {
  late ScrollController _scrollController;
  final logic = Get.find<BrandDetailLogic>();
  late int brandId;
  bool isFavorite = false;

  @override
  void initState() {
    super.initState();
    // 获取传递的参数
    brandId = Get.arguments;
    _scrollController = ScrollController();
    _scrollController.addListener(_scrollListener);
    logic.getBrandDetail(brandId);
    logic.getBrandList(brandId, isRefresh: true);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    // 当滚动到距离底部一定距离时触发加载
    if (_scrollController.position.extentAfter < 10 &&
        !logic.state.isLoading.value &&
        _scrollController.position.userScrollDirection == ScrollDirection.reverse) {
      logic.onLoadMore(brandId);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.grey,
      appBar: AppBar(
        backgroundColor: AppColor.white,
        toolbarHeight: 44,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, size: 20.0),
          onPressed: () {
            Get.back();
          },
        ),
        centerTitle: true,
        title: Text(Intl().brandDetailTitle, style: TextStyle(color: AppColor.black, fontSize: 14)),
      ),
      body: Obx(() {
        return SingleChildScrollView(
            controller: _scrollController,
            child: Padding(
                padding: EdgeInsets.only(left: 13.0, right: 13.0, bottom: 13.0),
                child: Column(
                  children: [
                    SizedBox(height: 10),
                    // 轮播图
                    _buildBanner(),
                    SizedBox(height: 10),
                    // 品牌
                    _buildBrand(),
                    SizedBox(height: 10),
                    // 品牌故事
                    _buildBrandStory(),
                    SizedBox(height: 10),
                    // 品牌推荐列表
                    _buildBrandProductList(),
                  ],
                )));
      }),
    );
  }

  /// 轮播图
  Widget _buildBanner() {
    final bannerUrl = logic.state.brandDetail.value?.bigPic;
    if (bannerUrl != null) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: Image.network(
          bannerUrl,
          errorBuilder: (context, error, stackTrace) {
            return SizedBox(height: 180);
          }
        ),
      );
    }

    return SizedBox(height: 180);
  }

  /// 品牌
  Widget _buildBrand() {
    final logoUrl = logic.state.brandDetail.value?.logo;
    return Container(
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Padding(
        padding: EdgeInsets.only(left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
        child: Row(
          children: [
            if (logoUrl != null)
              Image.network(
                logoUrl,
                height: 35.0,
              )
            else
              SizedBox.shrink(), // 防止布局异常，也可替换为默认图
            SizedBox(width: 15.0),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(logic.state.brandDetail.value?.name ?? '', style: TextStyle(fontSize: 16.0)),
                Text('品牌首字母: ${logic.state.brandDetail.value?.firstLetter ?? ''}',
                    style: TextStyle(fontSize: 10.0, color: AppColor.grey500)),
              ],
            ),
            Spacer(),
            IconButton(
              iconSize: 35.0,
              icon: Icon(
                isFavorite ? Icons.favorite : Icons.favorite_border,
                color: isFavorite ? Colors.red : Colors.grey,
              ),
              onPressed: () {
                setState(() {
                  isFavorite = !isFavorite;
                });
              },
            )
          ],
        ),
      ),
    );
  }

  /// 品牌故事
  Widget _buildBrandStory() {
    final story = logic.state.brandDetail.value?.brandStory;
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: AppColor.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Padding(
        padding: EdgeInsets.only(left: 15.0, right: 15.0, top: 10.0, bottom: 10.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text('品牌故事', style: TextStyle(fontSize: 16.0)),
            SizedBox(height: 15),
            Text(story ?? '', style: TextStyle(fontSize: 10.0, color: AppColor.grey500)),
          ],
        ),
      ),
    );
  }

  /// 品牌相关商品列表
  Widget _buildBrandProductList() {
    return Container(
        decoration: BoxDecoration(
          color: AppColor.white,
          borderRadius: BorderRadius.circular(10),
        ),
        child: Padding(
            padding: EdgeInsets.only(left: 5.0, right: 5.0, top: 10.0, bottom: 10.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(Intl().brandDetailRelated),
                SizedBox(height: 10),
                // 列表
                GridView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    mainAxisSpacing: 5.0,
                    crossAxisSpacing: 5.0,
                    childAspectRatio: 0.7,
                  ),
                  itemCount: logic.state.brandProductList.length,
                  itemBuilder: (context, index) {
                    return CommonProductVerticalWidget(
                        imageUrl: logic.state.brandProductList[index].pic,
                        title: logic.state.brandProductList[index].name,
                        content: logic.state.brandProductList[index].subTitle,
                        price: logic.state.brandProductList[index].price,
                        isShowContentMore: true);
                  },
                ),
                SizedBox(height: 8.0),
                Text(
                  !logic.state.hasMore.value
                      ? '没有更多数据了'
                      : (logic.state.isLoading.value ? '正在加载...' : '上拉加载更多'),
                  style: TextStyle(fontSize: 12.0, color: AppColor.grey500),
                )
              ],
            )));
  }
}
